package com.itheima.leyou.service;

import com.itheima.leyou.dao.OrderDao;
import com.itheima.leyou.util.StringUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderService {

    @Autowired
    RestTemplate restTemplate;
    /**
     * 秒杀政策redis Key前缀
     */
    private static final String STOCK_LIMIT_POLICY_ = "STOCK_LIMIT_POLICY_";
    /**
     * 提交订单队列key
     */
    private static final String ORDER_QUEUE = "order_queue";
    /**
     * 秒杀商品计数器
     */
    private static final String STOCK_POLICY_ = "STOCK_POLICY_";
    /**
     * 修改订单状态队列key
     */
    private static final String ORDER_STATUS_QUEUE = "order_status_queue";

    private static final String STORAGE_QUEUE = "storage_queue";
    /**
     * 引入redis
     */
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 引入rabbitMQ
     */
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Resource
    private OrderDao orderDao;

    public Map<String, Object> getOrder(String orderid){
        Map<String, Object> result = new HashMap<>();

        if (orderid==null||orderid.equals("")){
            result.put("result", false);
            result.put("msg", "订单编号不能为空！");
            return result;
        }

        return orderDao.getOrder(orderid);
    }

    @Transactional
    public Map<String, Object> createOrder(Map<String, Object> orderInfo) {

        Map<String, Object> result = new HashMap<>();

        if (orderInfo == null || orderInfo.isEmpty()) {
            result.put("result", false);
            result.put("msg", "订单数据为空，请刷新数据！");
            return result;
        }

        String sku_id = (String) orderInfo.get("sku_id");
        String limitPolicy = redisTemplate.opsForValue().get(STOCK_LIMIT_POLICY_ + sku_id);
        long orderId = System.nanoTime();
        String order_id = (orderId<0?-orderId:orderId) + "";
        //存在秒杀政策
        if (limitPolicy != null && !"".equals(limitPolicy)) {
            //秒杀政策转为map
            Map<String, Object> limitPolicyMap = StringUtil.mapStringToMap(limitPolicy);
            //秒杀商品的库存
            Integer quanty = Integer.valueOf(limitPolicyMap.get("quanty").toString());
            //说明还有
            if(redisTemplate.opsForValue().increment(STOCK_POLICY_+sku_id,1) <= quanty){
//                Map stockMap = restTemplate.getForObject("http://leyou-stock/getStockBySKU/" + sku_id, Map.class);
                //查不到有效的商品不能提交订单
//                if (stockMap == null || stockMap.isEmpty()) {
//                    return new HashMap();
//                }
                orderInfo.put("order_id", order_id);
                //实付金额
                orderInfo.put("actual_fee", limitPolicyMap.get("price"));
                //优惠活动id
                orderInfo.put("promotion_ids", limitPolicyMap.get("policyId"));
                //总金额
                orderInfo.put("total_fee", limitPolicyMap.get("price"));
                //支付类型,提交订单时为0
                orderInfo.put("payment_type", 0);
                //邮费
                orderInfo.put("post_fee", 0);
                //用户id
//                orderInfo.put("user_id", 1);
                //发票类型
                orderInfo.put("invoice_type", 0);
                //来源类型
                orderInfo.put("source_type", 0);
                //订单状态，待支付
                orderInfo.put("status", 0);
                //商品名称
                orderInfo.put("title", orderInfo.get("title"));
                //商品规则
                orderInfo.put("own_spec", "");
                //商品图片
                orderInfo.put("image", orderInfo.get("images"));
                //商品sku_id
                orderInfo.put("sku_id", orderInfo.get("sku_id"));
                try {
                    //提交订单交由队列处理
                    amqpTemplate.convertAndSend(ORDER_QUEUE,orderInfo.toString());
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("result", false);
                    result.put("msg", "订单写入队列失败，失败原因：【"+e.getMessage()+"】");
                    return result;
                }
            }else{
                result.put("result", false);
                result.put("msg", "秒杀商品已售空！");
                return result;
            }
        } else {
            result.put("result", false);
            result.put("msg", "秒杀活动已结束！");
            return result;
        }

        result.put("result", true);
        result.put("msg", "订单写入队列成功！");
        result.put("order_id", order_id);
        return result;
    }

    public Map<String, Object> updateOrderStatus(String orderid){
        Map<String, Object> map = new HashMap<>();
        if (orderid==null||orderid.equals("")){
            map.put("result", false);
            map.put("msg", "");
            return map;
        }

        boolean result = orderDao.updateOrderStatus(orderid);

        if (result){

            try {
                //减库存交由队列处理
                amqpTemplate.convertAndSend(STORAGE_QUEUE, "1_"+orderDao.getsku_id(orderid)+"_0_1");
            }catch (Exception e){
                e.printStackTrace();
                map.put("result", false);
                map.put("msg", "写入队列失败，失败原因：【"+e.getMessage()+"】");

            }
            map.put("result", true);
            map.put("msg", "");
        } else {
            map.put("result", false);
            map.put("msg", "更新订单"+orderid+"支付状态失败！");
        }
        return map;
    }

    /**
     * 支付成功
     * @param orderid
     * @return
     */
    public Map<String, Object> payOrder(String orderid){
        Map<String, Object> result = new HashMap<>();
        if (orderid==null||orderid.equals("")){
            result.put("result", false);
            result.put("msg", "无效的订单为空，不能支付！");
            return result;
        }
        try {
            //提交订单交由队列处理
            amqpTemplate.convertAndSend(ORDER_STATUS_QUEUE,orderid);
        }catch (Exception e){
            e.printStackTrace();
            result.put("result", false);
            result.put("msg", "支付失败，失败原因：【"+e.getMessage()+"】");
            return result;
        }
        result.put("result", true);
        result.put("msg", "支付成功！");
        return result;
    }

    /**
     * 根据sku_id查询订单明细
     * @param sku_id
     * @return
     */
    public List<Map<String,Object>> getOrderDetailListBySkuId(String sku_id){
        return orderDao.getOrderDetailListBySkuId(sku_id);
    }
}
